<template>
  <div>
    <el-card shadow="never">
      <el-form :inline="true">
        <el-button type="warning" :disabled="isDisabled" style="margin-left: 10px;" @click="dialogFormVisible = true">添加商品
        </el-button>
        <el-button type="primary" style="margin-right: 10px" :disabled="multipleSelection.length===0" @click="batchRemove()">批量删除</el-button>
        <el-form-item label="商品名">
          <el-input v-model="searchName" placeholder="请输入商品名进行查询"/>
        </el-form-item>
        <el-form-item label="上架时间（起始/截至）">
          <el-date-picker
              v-model="dateRange"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="起始日期"
              end-placeholder="截至日期"
          ></el-date-picker>
        </el-form-item>
        <el-button type="warning" :disabled="isDisabled" @click="resetData()">清空输入</el-button>
        <el-button type="warning" :disabled="isDisabled" @click="fetchData()">查询</el-button>
      </el-form>
    </el-card>
    <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        tooltip-effect="dark"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        max-height="450px"
        :header-cell-style="tableHeaderCellStyle"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="商品编号" width="120" sortable />
      <el-table-column label="商品图片" width="180">
        <template v-slot="scope">
          <img :src="scope.row.picture||require('@/assets/picture.png')" width="90px" height="90px" alt="">
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名" width="150" />
      <el-table-column prop="number" label="库存" width="150" sortable />
      <el-table-column prop="price" label="单价" width="150" sortable />
      <el-table-column prop="groupPrice" label="团购价" width="140" sortable />
      <el-table-column label="商品介绍" width="140">
        <template v-slot="scope">
          <el-tooltip effect="dark" content="点击查看详情" placement="top">
            <div style="cursor: pointer" @click="productIntro(scope.row.intro)">
              {{scope.row.intro===null? '':scope.row.intro.slice(0,20)+'...'}}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="groupNum" label="团购人数" width="140" sortable />
      <el-table-column prop="peoples" label="当前人数" width="140" sortable />
      <el-table-column prop="limitNum" label="单限" width="150" sortable />
      <el-table-column prop="updateTime" width="160" label="最近更新库存日期" sortable />
      <el-table-column width="150" fixed="right" label="操作">
        <template v-slot="scope">
          <el-button size="mini" type="warning" style="display: block" :disabled="isDisabled" @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button size="mini" type="primary" style="display: block;margin-left: 0;margin-top: 2px" :disabled="isDisabled" @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
          <el-button size="mini" type="warning" style="display: block;margin-left: 0;margin-top: 2px" :disabled="isDisabled" @click="handlePicture(scope.row)">上传图片
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="上传图片" :before-close="handleClose" :visible.sync="dialogPictureForm" :close-on-click-modal="false" width="26%" :destroy-on-close="true">
      <el-upload class="upload-demo" :file-list="fileList" ref="upload" drag action="" :auto-upload="false" :limit="1" :on-change="handleChange" :on-remove="handleRemove">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传一张图片,且大小不能超过1MB</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeForm">取 消</el-button>
        <el-button type="primary" @click="uploadPicture">上 传</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增 / 修改" :before-close="handleClose" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="50%" :destroy-on-close="true">
      <el-form :model="addForm" ref="Form" :rules="formRules">
        <div style="display: flex;justify-content: space-between">
          <div style="width: 45%">
            <el-form-item label="商品名" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入商品名" tabindex="2"></el-input>
            </el-form-item>
            <el-form-item label="库存" prop="number">
              <el-input v-model="addForm.number" placeholder="请输入库存数量" tabindex="2"></el-input>
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input v-model="addForm.price" type="number" placeholder="请输入单价" tabindex="2"></el-input>
            </el-form-item>
            <el-form-item label="团购价" prop="price">
              <el-input v-model="addForm.groupPrice" type="number" placeholder="请输入团购价" tabindex="2"></el-input>
            </el-form-item>
          </div>
          <div style="width: 45%">
            <el-form-item label="团购人数">
              <el-input v-model="addForm.groupNum" type="number" placeholder="请输入团购价" tabindex="2"></el-input>
            </el-form-item>
            <el-form-item label="单限">
              <el-input v-model="addForm.limitNum" type="number" placeholder="请输入团购价" tabindex="2"></el-input>
            </el-form-item>
            <el-form-item label="商品介绍">
              <el-input type="textarea" :rows="5" placeholder="请输入商品介绍" v-model="addForm.intro">
              </el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeForm">取 消</el-button>
        <el-button type="primary" @click="sendForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, deleteProduct, addOrUpdate, uploadPicture } from '@/api/product'
import { recordLog } from '@/api/recordLog'

export default {
  name: 'Product',
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      searchName: '',
      dateRange: [],
      dialogFormVisible: false,
      dialogPictureForm: false,
      addForm: {},
      formRules: {
        name: [{ required: true, message: '商品名不能为空', trigger: 'blur' }],
        number: [{ required: true, message: '库存值不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '单价值不能为空', trigger: 'blur' }]
      },
      loading: false,
      fileList: [],
      fileId: ''
    }
  },
  computed: {
    isDisabled: function() {
      return this.multipleSelection.length !== 0
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    productIntro(intro){
      this.$alert(intro,'商品介绍',{
        showConfirmButton: false
      })
    },
    tableHeaderCellStyle () {
      return 'background-color: #fcf3ec;'
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    // 选中处理
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 修改
    handleEdit(index, row) {
      this.addForm = {
        id: row.id,
        name: row.name,
        number: row.number,
        price: row.price,
        groupPrice: row.groupPrice,
        intro: row.intro,
        groupNum: row.groupNum,
        limitNum: row.limitNum
      }
      this.dialogFormVisible = true
    },
    handleClose() {
      this.addForm = {}
      this.fileId = ''
      this.fileList = []
      this.dialogFormVisible = false
      this.dialogPictureForm = false
    },
    closeForm() {
      this.addForm = {}
      this.fileId = ''
      this.fileList = []
      this.dialogFormVisible = false
      this.dialogPictureForm = false
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm(`是否删除${row.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = new Array(1).fill(row.id)
        deleteProduct(ids).then(response => {
          recordLog({ username: this.$store.getters.username, operate: '删除商品' })
          this.$message({
            type: 'success',
            message: '删除成功!',
            center: true
          })
          this.fetchData()
        })
      })
    },
    fetchData() {
      const searchObj = {}
      if (this.searchName !== '') {
        searchObj.name = this.searchName
      }
      if (this.dateRange.length !== 0) {
        searchObj.begin = this.dateRange[0]
        searchObj.end = this.dateRange[1]
      }
      this.loading = true
      getList(searchObj).then(response => {
        response.data.forEach(item => {
          if (item.picture !== null) {
            item.picture = process.env.VUE_APP_BASE_API + item.picture
          }
        })
        this.tableData = response.data
        this.loading = false
      })
    },
    resetData() {
      this.searchName = ''
      this.dateRange = []
      this.fetchData()
    },
    batchRemove() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先选择需要删除的商品',
          type: 'warning',
          center: true
        })
        return
      }
      this.$confirm('是否删除选中的数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.multipleSelection.map(item => {
          return item.id
        })
        deleteProduct(ids).then(response => {
          recordLog({ username: this.$store.getters.username, operate: '删除商品' })
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
      })
    },
    sendForm() {
      this.$refs.Form.validate(valid => {
        if (valid) {
          addOrUpdate(this.addForm).then(response => {
            if (this.addForm.id === '' || this.addForm.id === undefined) {
              recordLog({ username: this.$store.getters.username, operate: `添加商品${this.addForm.name}` })
            } else {
              recordLog({ username: this.$store.getters.username, operate: `修改商品${this.addForm.name}信息` })
            }
            this.addForm = {}
            this.dialogFormVisible = false
            this.fetchData()
            this.$message({
              message: '更改成功',
              type: 'success',
              center: true
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handlePicture(row) {
      this.fileId = row.id
      this.dialogPictureForm = true
    },
    uploadPicture() {
      if (this.fileList.length === 0) {
        this.$message({
          message: '请选择文件后上传',
          type: 'warning',
          center: true
        })
        return
      }
      const isLt1M = this.fileList[0].raw.size / 1024 / 1024 < 1
      if (!isLt1M) {
        this.$message({
          message: '上传图片大小不能超过 1MB!',
          type: 'error',
          center: true
        })
        return
      }
      const formData = new FormData()
      formData.append('id', this.fileId)
      formData.append('picture', this.fileList[0].raw)
      uploadPicture(formData).then(res => {
        this.$message({
          message: '上传成功',
          type: 'success',
          center: true
        })
        this.fetchData()
        this.dialogPictureForm = false
      })
    }
  }
}
</script>

<style scoped>
.el-button--warning.is-active,
.el-button--warning:active {
  background: #4d4c50;
  border-color: #4d4c50;
  color: #fff;
}

.el-button--warning:focus,
.el-button--warning:hover {
  background: #575559;
  border-color: #575559;
  color: #fff;
}

.el-button--warning {
  color: #FFF;
  background-color: #4d4c50;
  border-color: #4d4c50;
}

.el-button--primary.is-active,
.el-button--primary:active {
  background: #f79d36;
  border-color: #f79d36;
  color: #fff;
}

.el-button--primary:focus,
.el-button--primary:hover {
  background: #f8a03b;
  border-color: #f8a03b;
  color: #fff;
}

.el-button--primary {
  color: #FFF;
  background-color: #f79d36;
  border-color: #f79d36;
}
</style>
